package com.boss.common;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.Base64;

/**
 * 加密工具类，提供AES加密和解密功能
 *
 * @author 郑炆杰
 */
public class EncryptionUtils {
    private static final String SECRET_KEY = "1234567890123456";
    private static final String ALGORITHM = "AES";
    private static final String MODE_PADDING = "AES/ECB/PKCS5Padding";

    private EncryptionUtils() {
        // 私有构造方法，防止外部实例化
    }

    /**
     * AES加密方法
     *
     * @param plainText 明文字符串
     * @return 加密后的Base64编码字符串
     * @throws EncryptionException 加密过程中发生的异常，包装并抛出
     */
    public static String encrypt(String plainText) throws EncryptionException {
        try {
            Cipher cipher = Cipher.getInstance(MODE_PADDING);
            Key secretKey = new SecretKeySpec(SECRET_KEY.getBytes(), ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
            return Base64.getEncoder().encodeToString(encryptedBytes);
        } catch (Exception e) {
            throw new EncryptionException("加密失败", e);
        }
    }

    /**
     * AES解密方法
     *
     * @param encryptedText 经过Base64编码的加密字符串
     * @return 解密后的明文字符串
     * @throws EncryptionException 解密过程中发生的异常，包装并抛出
     */
    public static String decrypt(String encryptedText) throws EncryptionException {
        try {
            Cipher cipher = Cipher.getInstance(MODE_PADDING);
            Key secretKey = new SecretKeySpec(SECRET_KEY.getBytes(), ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
            return new String(decryptedBytes);
        } catch (Exception e) {
            throw new EncryptionException("解密失败", e);
        }
    }
}
